package http

import (
	"gitee.com/saxon134/go-utils/saData"
	"gitee.com/saxon134/go-utils/saData/saError"
	"gitee.com/saxon134/go-utils/saHttp"
	"gitee.com/saxon134/workflow/api"
	"gitee.com/saxon134/workflow/conf"
	"gitee.com/saxon134/workflow/errs"
	"github.com/gin-gonic/gin"
	"strconv"
	"time"
)

type AuthType int8

const (
	AuthNull AuthType = iota
	AuthSign
	AuthMs
)

// 权限校验
func authCheck(c *api.Context, auths ...AuthType) (err error) {
	if auths == nil || len(auths) == 0 {
		return nil
	}
	if len(auths) == 1 && auths[0] == AuthNull {
		return nil
	}

	gc, _ := c.Context.(*gin.Context)
	for _, t := range auths {
		if t != AuthNull {
			if err = check(c, gc, t); err != nil {
				return err
			}
		}
	}
	return nil
}

func check(c *api.Context, gc *gin.Context, t AuthType) error {
	if t == AuthSign {
		sign := gc.GetHeader("sign")
		timestamp, _ := saData.ToInt64(gc.GetHeader("timestamp"))
		if sign == "" || timestamp <= 0 || (timestamp > time.Now().Unix()+5) || timestamp < 1627607322 {
			return saError.StackError(errs.ErrorUnauthorized)
		}

		sign2 := conf.Conf.Http.SignSecret + strconv.FormatInt(timestamp, 10)
		sign2 = saData.Md5(sign2, true)
		if sign2 != sign {
			return saError.StackError(errs.ErrorUnauthorized)
		}
	}

	if t == AuthMs {
		token := gc.GetHeader("Authorization")
		if token == "" {
			return saError.StackError(errs.ErrorUnLogged)
		}

		_ = saHttp.JwtParse(token, conf.Conf.Http.JwtSecret, &c.Account)
		if c.Account.Id <= 0 {
			return saError.StackError(errs.ErrorLoggedFail)
		}

		//todo 需要获取应用 & 客户信息，进而进一步检验权限
		//todo 如果是超级管理员身份，可以放行
		return nil
	}

	return nil
}
